<?php

namespace app\lib\token;

use Firebase\JWT\JWT;
use think\facade\Request;

class JwtToken
{
    // 密钥
    protected $secret;
    // 超时时间
    protected $exp = 7200;
    /**
     * 实列
     *
     * @var self
     */
    protected static $instance;
    
    // 标准负载
    protected $stdPayload = [];

    public function __construct()
    {
        $this->secret = env('APP_SECRET', 'you secret key');
        $this->exp = env('TOKEN.EXP', 7200);
        // 签发时间
        $this->stdPayload['iat'] = time();
        // 过期时间
        $this->stdPayload['exp'] = time() + $this->exp;
    }

    /**
     * 获取实列
     *
     * @return self
     */
    public static function getInstance()
    {
        if(self::$instance){
            return self::$instance;
        }
        self::$instance = new self;
        return self::$instance;
    }

    /**
     * 签发jwt
     *
     * @param array $payload
     * @return string
     */
    public static function grant(array $payload):string
    {
        $ins = self::getInstance();
        $payload = array_merge($ins->stdPayload,$payload);
        $jwt = JWT::encode($payload, $ins->secret);
        return $jwt;
    }


    /**
     * 根据header获取jwt
     *
     * @return string
     */
    public static function getFromHeader(): string
    {
        $tokenjwt = Request::instance()->header('Authorization');
        return empty($tokenjwt) ? false : $tokenjwt;
    }


    /**
     * 解析jwt获取其中的数据
     *
     * @return array|boolean
     */
    public static function getValues()
    {
        $tokenjwt = self::getFromHeader();
        if (! $tokenjwt) {
            return false;
        }
        $ins = self::getInstance();
        try {
            $val = JWT::decode($tokenjwt, $ins->secret,['HS256']);
        } catch (\Throwable $th) {
            return false;
        }
        return array($val);
    }
}